package com.yakaten.service;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.seasar.framework.util.ResourceUtil;

import au.com.bytecode.opencsv.CSVWriter;

import com.yakaten.dto.YahooPriceTaskDto;
import com.yakaten.exception.SystemException;
import com.yakaten.logic.YahooPriceLogic;

public class YahooPriceRunner extends Thread {
	static Logger logger = Logger.getLogger(YahooPriceRunner.class);

	private static final SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	String SHOP_NAME = ResourceUtil.getProperties("yakaten.properties")
	.getProperty("system.shopName");

	public static int KENKAKU = 10;

	public static SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmm00");

	private MakeShopItemService makeShopItemService = new MakeShopItemService();

	public void start() {
		super.start();
	}

	public List<YahooPriceTaskDto> getWorkList() {
		List<YahooPriceTaskDto> workList = new ArrayList<YahooPriceTaskDto>();
		YahooPriceLogic logic = new YahooPriceLogic();

		//get all task
		List<YahooPriceTaskDto> taskList;
		try {
			taskList = logic.getAllTaskList();
		} catch (SystemException e) {
			logger.error(e);
			return workList;
		}

		Iterator<YahooPriceTaskDto> taskListIt = taskList.iterator();

		while (taskListIt.hasNext()) {
			YahooPriceTaskDto currentTask = taskListIt.next();
			if (currentTask.getStatus() == 1) {
				//get newest price from self shop
				try {
					Map<String ,String> shopItemInfo = makeShopItemService.getItemInfoByHtml(currentTask.getShopItemId());
					try {
						YahooPriceRunner.sleep(1* 1000);
					} catch (InterruptedException e) {
						logger.error(e);
					}
					String itemName = shopItemInfo.get("itemName");
					String itemPrice = shopItemInfo.get("itemPrice");

					if(itemName!=null && itemPrice !=null){
						long itemPriceLong = Long.parseLong(itemPrice);
//						if(currentTask.getShopItemPrice() != itemPriceLong){
							//price changed
							long workPrice = itemPriceLong;
							if(currentTask.getComparePricePer() !=0){
								double rate = (double)currentTask.getComparePricePer();
								workPrice = (long)(itemPriceLong * (1+rate/100));
							}

							if(currentTask.getComparePrice()!=0){
								workPrice = workPrice+currentTask.getComparePrice();
							}

							if(workPrice >= currentTask.getMinPrice()){
								currentTask.setWorkPrice(workPrice);
								currentTask.setYahooItemPrice(workPrice);
								currentTask.setShopItemPrice(itemPriceLong);
								workList.add(currentTask);
							}
//						}
					}
				} catch (Exception e) {
					logger.error(e);
				}
			}

		}
		return workList;
	}

	public boolean updateYahoo(List<YahooPriceTaskDto> workList){

		boolean result=false;
		CSVWriter writer = null;

		String csvFilePath =ResourceUtil.getProperties("yakaten.properties").getProperty("yahoo.price.filepath");
		String csvFileName =ResourceUtil.getProperties("yakaten.properties").getProperty("yahoo.price.filename");
		String csvFileEncoding =ResourceUtil.getProperties("yakaten.properties").getProperty("yahoo.price.filencoding");
		Calendar calendar =Calendar.getInstance();
		Date execDate = new Date();
		execDate.setTime(calendar.getTime().getTime()+2*60*1000);
		csvFileName = csvFileName.replace("{0}", format.format(execDate));
		try {
			writer = new CSVWriter(new OutputStreamWriter(new FileOutputStream(csvFilePath+csvFileName),csvFileEncoding), ',');
			String []csvHeader = {"path","name","code","price","sale-price"};
			writer.writeNext(csvHeader);
			for(YahooPriceTaskDto current:workList){
				String [] csvData = new String[5];
				csvData[0]=current.getYahooItemCategory();//category
				csvData[1]=current.getYahooItemName();//itemname
				csvData[2]=current.getYahooItemId();//itemId
				csvData[3]=""+current.getWorkPrice();//price
				csvData[4]="";//price
				writer.writeNext(csvData);
			}


		} catch (IOException e) {
			logger.error(e);
			return result;
		}finally {
			try {
				if (writer != null) {
					writer.close();
				}
			} catch (IOException e) {
				logger.error(e);
			}
		}

		result = new YahooFtpService().upLoadPriceFile(csvFilePath, csvFileName);
		return result;
	}


	public static void main(String [] args){

//		System.getProperties().put("proxySet", "true");
//
//		System.getProperties().put("proxyPort", "80");
//
//		System.getProperties().put("proxyHost", "proxysv");
//
		YahooPriceRunner runner = new YahooPriceRunner();
		List<YahooPriceTaskDto> workList  = runner.getWorkList();
//		if(workList.size()>0&&runner.updateYahoo(workList)){
//			YahooPriceLogic logic = new YahooPriceLogic();
//			try {
//				logic.updateTask(workList);
//			} catch (SystemException e) {
//				e.printStackTrace();
//			}
//		}
//		List<YahooPriceTaskDto> list= new ArrayList<YahooPriceTaskDto>();
//		YahooPriceTaskDto dto = new YahooPriceTaskDto();
//		dto.setYahooItemCategory("liu test");
//		dto.setYahooItemName("liu test01");
//		dto.setYahooItemId("test01");
//		dto.setWorkPrice(999);
//		list.add(dto);
//		runner.updateYahoo(list);

//		long price = 91740;
//		double rate =12;
//		long workPrice = (long)(91740 * (1 +rate/100));
//		System.out.println(rate/100);
//		System.out.println(workPrice);
	}

	public void run() {
		while (true) {
			try{
				if("1".equals(ResourceUtil.getProperties("yakaten.properties").getProperty("yahoo.price.runner.run"))){
					if(logger.isInfoEnabled()){
						String message = "--------yahoo task start on:"+sf.format(new Date())+"---------";
						logger.info(message);
					}

					List<YahooPriceTaskDto> workList = getWorkList();
					if(workList.size()>0){
						if(updateYahoo(workList)){
							YahooPriceLogic logic = new YahooPriceLogic();
							logic.updateTask(workList);
						}
					}
				}

			}catch(Exception e){
				logger.error(e);
			}finally{
				if(logger.isInfoEnabled()){
					String message = "--------yahoo task end on:"+sf.format(new Date())+"---------";
					logger.info(message);
				}
			}

			try {
				YahooPriceRunner.sleep(KENKAKU  *60* 1000);
			} catch (InterruptedException e) {
				logger.error(e);
			}
		}
	}

}
